package com.tdt.alarm.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;

import com.tdt.alarm.model.AlarmContract.Setting;

public class SettingDBHelper extends SQLiteOpenHelper {

	public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "setting.db";
    /**
     * Create Database
     */
	private static final String SQL_CREATE_SETTING = 
		"CREATE TABLE " + Setting.TABLE_NAME_SETTING + " (" +
				Setting._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
		Setting.COLUMN_NAME_SETTING_SNOOZE_METHOD + " INTEGER," +
		Setting.COLUMN_NAME_SETTING_RINGTONE + " TEXT" + " )";

	/**
	 * Drop database
	 */
	private static final String SQL_DELETE_SETTING =
		    "DROP TABLE IF EXISTS " + Setting.TABLE_NAME_SETTING;

	public SettingDBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_SETTING);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL(SQL_DELETE_SETTING);
        onCreate(db);
	}
	
	/**
	 * Get one SettingModel
	 * @param c
	 * @return a SettingModel
	 */
	private SettingModel populateModel(Cursor c) {
		
		long id = c.getLong(c.getColumnIndex(Setting._ID));
        Uri ringtone = Uri.parse(c.getString(c.getColumnIndex(Setting.COLUMN_NAME_SETTING_RINGTONE)));
        int snoozeMethod = c.getInt(c.getColumnIndex(Setting.COLUMN_NAME_SETTING_SNOOZE_METHOD));
        
        SettingModel model = new SettingModel(id, snoozeMethod, ringtone);
        return model;
    }
 
	/**
	 * Put value of SettingModel to ContentValues
	 * @param model
	 * @return ContentValues
	 */
    private ContentValues populateContent(SettingModel model) {
        ContentValues values = new ContentValues();
        values.put(Setting._ID, model.getId());
        values.put(Setting.COLUMN_NAME_SETTING_RINGTONE, model.getRingtone().toString());
        values.put(Setting.COLUMN_NAME_SETTING_SNOOZE_METHOD, model.getSnoozeMethod());
        return values;
    }
    
    /**
     * Write a SettingModel to DB
     * @param model
     * @return id of this SettingModel
     */
    public long createSetting(SettingModel model) {
        ContentValues values = populateContent(model);
        return getWritableDatabase().insert(Setting.TABLE_NAME_SETTING, null, values);
    }
 
    /**
     * get a SettingModel im DB by ID
     * @param id
     * @return
     */
    public SettingModel getSetting(long id) {
        SQLiteDatabase db = this.getReadableDatabase();
 
        String select = "SELECT * FROM " + Setting.TABLE_NAME_SETTING + " WHERE " + Setting._ID + " = " + id;
 
        Cursor c = db.rawQuery(select, null);
 
        if (c.moveToNext()) {
            return populateModel(c);
        }
 
        return null;
    }
    
    /**
     * Update SettingModel in DB
     * @param model
     * @return
     */
    public long updateSetting(SettingModel model) {
        ContentValues values = populateContent(model);
        return getWritableDatabase().update(Setting.TABLE_NAME_SETTING, values, Setting._ID + " = ?", new String[] { String.valueOf(model.getId()) });
    }
 
    /**
     * Delete SettingModel im DB by ID
     * @param id
     * @return how many row effect (default by 1)
     */
    public int deleteSetting(long id) {
        return getWritableDatabase().delete(Setting.TABLE_NAME_SETTING, Setting._ID + " = ?", new String[] { String.valueOf(id) });
    }
    
    /**
     * Get all SetSetting in DB
     * @return
     */
    public List<SettingModel> getSettings() {
        SQLiteDatabase db = this.getWritableDatabase();
        if(db == null){
        	Log.i("DB Exeption", "DB is not readable !");
        	return null;
        }
        String select = "SELECT * FROM " + Setting.TABLE_NAME_SETTING;
 
        Cursor c = db.rawQuery(select, null);
 
        List<SettingModel> settingList = new ArrayList<SettingModel>();
 
        while (c.moveToNext()) {
            settingList.add(populateModel(c));
        }
 
        if (!settingList.isEmpty()) {
        	Collections.reverse(settingList);
            return settingList;
        }
 
        return null;
    }
    
 // get setting at first
 	public SettingModel getFirstSetting() {
 		List<SettingModel> listSetting = getSettings();
 		if (listSetting == null || listSetting.size() == 0) {
 			SettingModel model = new SettingModel(0, 1,
 					RingtoneManager
 							.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
 			createSetting(model);
 			return getFirstSetting();
 		} else {
 			return listSetting.get(0);
 		}
 	}
}